package common.mq.active;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by dong peng on 2018/1/28.
 */
public class QueueProducer {

    public static void main(String[] args) throws JMSException {
        System.out.println(
                ActiveMQConnectionFactory.DEFAULT_USER + ", " +
                        ActiveMQConnectionFactory.DEFAULT_PASSWORD + ", "+
                        ActiveMQConnectionFactory.DEFAULT_BROKER_URL
        );

        QueueProducer acmq = new QueueProducer();

        // 3. 创建session上下文，一些配置参数，比如是否使用事务
        Connection connection = acmq.createConn();
        Session session =  connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);

        // 4.通过Session创建Destionation对象， 在PTP模式下是queue， 在pub/sub是Topic
        Destination destination = session.createQueue("queue1");

        // 5.通过session创建，发送消息的生产者
        MessageProducer producer = session.createProducer(destination);

        // 6.设置持久化/非持久化特性  非持久化则会丢失数据   如果持久化kahdb/levedb/jdbc
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        // 7. 定义消息对象，并发送
        for(int i = 0; i< 10000; i++) {
            TextMessage textMessage = session.createTextMessage();
            textMessage.setText("Hello ActiveMQ" + i);
            producer.send(textMessage);
        }


        // 必须要关闭，不然activemq不会释放
        if(connection != null) {
            connection.close();
        }
    }

    public Connection createConn() throws JMSException {
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
                ActiveMQConnectionFactory.DEFAULT_USER,
                ActiveMQConnectionFactory.DEFAULT_PASSWORD,
                ActiveMQConnectionFactory.DEFAULT_BROKER_URL
        );

        // 注意Connection默认是关闭，所以需要start开启
        Connection connection = connectionFactory.createConnection();
        connection.start();

        return connection;
    }
}
